<template>
    <div class="content">
        <!--头部-->
        <div class="header-setting">
            <a-breadcrumb class="breadcrumb">
                <a-breadcrumb-item>
                    <a href="../main">首页</a>
                </a-breadcrumb-item>
                <a-breadcrumb-item>系统设置</a-breadcrumb-item>
                <a-breadcrumb-item>月卡购买记录</a-breadcrumb-item>
            </a-breadcrumb>
            <!--查询条件-->
            <div class="box-condition-body">
                <div class="box-condition-item">
                    <div style="margin: 0 50px">月卡名称</div>
                    <template>
                        <a-input
                                style="margin: 0 200px 0 50px" placeholder="月卡名称" v-model="inputCardName"
                                @change="selectChange"/>
                    </template>

                    <div style="margin: 0 50px">车牌号</div>
                    <template>
                        <a-input
                                style="margin: 0 200px 0 50px" placeholder="车牌号" v-model="inputLicencePlate"
                                @change="selectChange"/>
                    </template>

                    <a-row style="margin-top:0.5em">
                        <a-col :span="6">支付时间</a-col>
                        <a-col :span="16">
                            <a-range-picker
                                    id="range-picker"
                                    :showTime="{
                                format: 'HH:mm:ss'
                            }"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="['开始时间', '结束时间']"
                                    @ok="onOkPop"
                                    @change="onChangePop"
                                    :value="rangePickerValuePop()"/>
                        </a-col>
                    </a-row>
                </div>
            </div>

        </div>

        <!-- 表内容 -->
        <div class="box-form">
            <!--工具栏-->
            <div class="box-tool">
                <div></div>
                <div style="display: flex">
                    <a-button type="primary" @click="exportExcel" icon="download">导出</a-button>
                </div>
            </div>

            <!--数据表格-->
            <div class="box-table">
                <a-table
                        rowKey="no"
                        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:'3.5%'}"
                        :columns="columns"
                        :dataSource="entryExitRecordList"
                        :pagination="pagination"
                        @change="tableTabSort"
                        bordered size="small"
                        :scroll="scroll">

                    <template slot="amount" slot-scope="text">
                        <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
                    </template>
                    <template slot="operate" slot-scope="text,data">
                        <a v-on:click="refundWindows(data)">退款</a>
                    </template>
                </a-table>
            </div>
        </div>
        <!-- 退款弹窗 -->
        <a-modal
        title="退款"
        v-model="refundPopupData.visible"
        :confirmLoading="refundPopupData.loading"
        @cancel="() => {this.hideRefundPopupData();}"
        @ok="refund">
        <a-row style="margin-top: 0.5em">
        <a-col :span="6">订单金额</a-col>
        <a-col :span="15">
            <a-input disabled v-model="refundPopupData.amount" type="text,data" />
        </a-col>
        </a-row>
        <a-row style="margin-top: 0.5em">
        <a-col :span="6">退款金额</a-col>
        <a-col :span="15">
            <a-input
            placeholder="退款金额(元)"
            defaultValue="2"
            v-model="refundPopupData.money"
            type="text"
            onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            />
        </a-col>
        </a-row>
        <span>
        <a-row style="margin-top: 0.5em">
            <a-col :span="6">退款备注</a-col>
            <a-col :span="15">
            <a-textarea
                maxlength="100"
                placeholder="退款备注"
                v-model="refundPopupData.remark"
            />
            </a-col>
        </a-row>
        </span>
    </a-modal>
    </div>
</template>

<script>
    import moment from 'moment';
    import Constant from "../../utils/Constant";
    import MonthCardApi from "../../api/system/MonthCardManage";
    import ParkingRecordApi from "../../api/charge/ChargeDetail";
    // import CommonApi from "../../api/CommonApi";
    const columns = [
        {
            title: "月卡名称",
            dataIndex: "cardName",
            width: '11%',
        },
        {
            title: "购买用户",
            dataIndex: "account",
            width: '11%',
        },
        {
            title: "用户车牌",
            dataIndex: "licencePlate",
            width: '11%',
        },
        {
            title: "本地单号",
            dataIndex: "outTradeNo",
            width: '11%',
        },
        {
            title: "商户单号",
            dataIndex: "transactionOrderNo",
            width: '8%',
        },
        {
            title: "支付金额(单位：元)",
            dataIndex: "amount",
            scopedSlots: {customRender: 'amount'},
            width: '10%'
        },
        {
            title: "支付时间",
            dataIndex: "orderTime",
            width: '10%'
        },
        {
            title: "月卡开始时间",
            dataIndex: "startTime",
            width: '10%',
        },
        {
            title: "月卡结束时间",
            dataIndex: "endTime",
            width: '10%',
        },
        {
            title: "操作",
            scopedSlots: {customRender: 'operate'},
            width: '7%',
        },
    ];

    /*设备查询条件*/
    const conditionOfCard = {
        cardName: "",
        limit: "10",
        curr: "1"
    };

    export default {
        name: "MonthCardRecord",

        data() {
            return {
                /*查询条件*/
                conditionOfCard,
                inputCardName: '',
                inputLicencePlate: '',

                /*当前选中的行数据*/
                entryExitRecordList: [],
                columns,
                selectId: -1,
                parks: [],

                /*分页插件*/
                pagination: {
                    showTotal: total => `共${total}条`,
                    total: 0,
                    defaultCurrent: 1,
                    showQuickJumper: true,
                    current: 1,
                    defaultPageSize: 10
                },

                title: '',
                cardName: '',
                isValid: '',
                startTime: '',
                endTime: '',

                /*时间日期*/
                momentArr: [],
                momentArrPop: [],

                /* 表单选择 */
                selectedRowKeys: [],            /* 选择key */
                /*表格固定头部*/
                scroll: {
                    y: 550,
                },
                 /* 订单退款 */
                refundPopupData: {
                    visible: false,
                    loading: false,
                    wid: "",
                    money: "",
                    type: "",
                    remark: "",
                    payType: "",
                    amount:"",
                    orderTime:""
                },
            }
        },

        mounted() {
            this.initData();
        },

        methods: {
            initData() {
                this.loadDeviceList();
            },
            /* ---------------- 导出功能 ---------------- */
            exportExcel() {
                /* ---- condition ---- */
                let condition = this.conditionOfCard;
                condition.cardName = this.inputCardName;
                condition.licencePlate = this.inputLicencePlate;
                condition.startTime = this.startTime;
                condition.endTime = this.endTime;

                MonthCardApi.exportChargeExcel(condition)
                    .then((res) => {
                        const link = document.createElement("a");
                        const blob = new Blob([res.data], {
                            type: "application/vnd.ms-excel",
                        });
                        link.href = URL.createObjectURL(blob);
                        var fileName = decodeURIComponent(res.headers.filename);
                        if (fileName == null || fileName == "undefined") {
                            fileName = "月卡购买详情.xlsx";
                        }
                        link.style.display = "none";

                        link.setAttribute("download", `${fileName}`);
                        link.click();
                    })
                    .catch((err) => {
                        console.log("error");
                        console.log(err);
                        let data = err.data;
                        if (data) {
                            return this.$message.warn(data);
                        }
                    });
            },
            /* ---------------- 退款操作 ---------------- */
            hideRefundPopupData() {
            this.refundPopupData.visible = false;
            this.refundPopupData.wid = "";
            this.refundPopupData.money = "";
            this.refundPopupData.remark = "";
            this.refundPopupData.payType = "";
            this.refundPopupData.amount = "";
            this.refundPopupData.orderTime="";
            },
            refundWindows(data){
            this.refundPopupData.visible = true;
            this.refundPopupData.loading = false;
            this.refundPopupData.wid = data.id;
            this.refundPopupData.payType = data.payType;
            this.refundPopupData.amount = data.amount/100;
            this.refundPopupData.orderTime=data.orderTime;
            },
            refund(){
            this.refundPopupData;
            if (this.refundPopupData.wid == null || this.refundPopupData.wid == "" || this.refundPopupData.wid == undefined) {
                this.$message.warn("wid参数不能为空！");
                return;
            }
            if (
                this.refundPopupData.money == null ||
                this.refundPopupData.money == "" ||
                this.refundPopupData.money == undefined ||
                this.refundPopupData.money == "0" ||
                this.refundPopupData.money == 0
            ) {
                this.$message.warn("退款金额不为为0或空！");
                return;
            }
            if (this.refundPopupData.money > this.refundPopupData.amount) {
                this.$message.warn("退款金额不能超过订单金额！");
                return;
            }
            let type = 2;
            if (
              new Date().getFullYear() == new Date(this.orderTime).getFullYear() &&
              new Date().getMonth() == new Date(this.orderTime).getMonth() &&
              new Date().getDay() == new Date(this.orderTime).getDay()
            ){
              type = 1;
            }
            //0:订单 1:活动 2:包月
            this.refundPopupData.sourceType=2;
            this.refundPopupData.type=type;
            this.refundPopupData.money=this.refundPopupData.money * 100
            ParkingRecordApi.channelRefund(this.refundPopupData)
                .then((data) => {
                    let code = data.code;
                    if (code === 2000) {
                        this.$message.success("退款申请成功！");
                        this.hideRefundPopupData();
                        this.initData();
                    } else {
                        this.$message.error("退款申请失败1！" + data.msg);
                    }
                }).catch((error) => {
                    console.log(error)
                    this.$message.error("退款申请失败2!" + error);
                });
            console.log(this.refundPopupData)
            },

            /* --------------- 设备查询条件 --------------- */
            /* 有效状态 */
            tableTabSort(pagination, filters, sorter) {
                let sortType = undefined;
                let sortField = undefined;
                if (sorter) {
                    let {order, columnKey} = sorter;
                    if (order === "descend") {
                        sortType = 0;
                    } else if (order == 'ascend') {
                        sortType = 1;
                    }

                    if (columnKey == 'sn') {
                        sortField = 0;
                    } else if (columnKey == 'device_name') {
                        sortField = 1;
                    } else if (columnKey == 'device_type') {
                        sortField = 2;
                    } else if (columnKey == 'is_valid') {
                        sortField = 3;
                    }
                }

                this.conditionOfCard.sortType = sortType;
                this.conditionOfCard.sortField = sortField;
                this.loadDeviceList(pagination.current);
            },

            selectChange() {
                this.loadDeviceList()
            },

            /* --------------- 查询设备列表 --------------- */
            loadDeviceList(pageNum) {
                this.clearSelectArray();

                /* ---- condition ---- */
                let condition = this.conditionOfCard;
                condition.cardName = this.inputCardName;
                condition.licencePlate = this.inputLicencePlate;
                condition.curr = pageNum || 1;
                if (this.momentArrPop == undefined || this.momentArrPop.length == 0) {
                    this.momentArrPop[0] = moment().month(moment().month()).startOf("month");
                    this.momentArrPop[1] = moment().month(moment().month()).endOf("month");
                }
                condition.startTime = this.startTime;
                condition.endTime = this.endTime;

                /* ---- 查询 ---- */
                MonthCardApi.getMonthCardRecordList(condition)
                    .then((data) => {
                        let {list, total, pageNum, pageSize} = data.data;
                        let array = list || [];
                        array = array.map((item, index) => {
                            return {...item, no: total - (pageNum - 1) * pageSize - index};
                        })
                        this.entryExitRecordList = array;
                        this.pagination.total = total;
                        this.pagination.current = pageNum;
                    })
                    .catch((err) => {
                        this.$message.error(err)
                    });
            },

            /* ---------------- 选中处理 ------------------- */
            getSelectArray() {
                let entryExitRecordList = this.entryExitRecordList || [];
                let selectedRowKeys = this.selectedRowKeys;
                return entryExitRecordList.filter(item => {
                    return selectedRowKeys.filter(no => no == item.no).length > 0;
                })
            },

            clearSelectArray() {
                this.selectedRowKeys = [];
            },

            /* ----------------------------------------- */
            onSelectChange(selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys;
            },

            /*时间按钮控制*/
            button_time(e, type) {
                //type 1 日志 2 心跳
                this.selectId = e;
                let momentStart;
                let momentEnd;
                switch (e) {
                    case 0:
                        momentStart = moment().startOf('day');
                        momentEnd = moment().endOf('day');
                        break;
                    case 1:
                        momentStart = moment().add('day', -1).startOf('day');
                        momentEnd = moment().add('day', -1).endOf('day');
                        break;
                    case 2:
                        momentStart = moment().week(moment().week()).startOf('week');
                        momentEnd = moment().week(moment().week()).endOf('week');
                        break;

                    case 3:
                        momentStart = moment().week(moment().week() - 1).startOf('week');
                        momentEnd = moment().week(moment().week() - 1).endOf('week');
                        break;
                    case 4:
                        momentStart = moment().month(moment().month()).startOf('month');
                        momentEnd = moment().month(moment().month()).endOf('month');
                        break;
                    default :
                        break;
                }
                this.momentArr[0] = momentStart;
                this.momentArr[1] = momentEnd;
            },

            /*日期选择*/
            heartbeatOnChange(date) {
                this.selectId = -1;
                this.momentArr = date;
                if (date == undefined || date.length == 0) {
                    this.onOk(2);
                }
            },

            onOk(type) {
                this.selectId = -1;
            },

            rangePickerValue() {
                return this.momentArr;
            },

            setTime(fmt) {
                const time = new Date(fmt);
                const Y = time.getFullYear()
                const M = (time.getMonth() + 1).toString().padStart(2, '0')
                const D = time.getDate().toString().padStart(2, '0')
                const h = time.getHours().toString().padStart(2, '0')
                const m = time.getMinutes().toString().padStart(2, '0')
                const s = time.getSeconds().toString().padStart(2, '0')
                return `${Y}-${M}-${D} ${h}:${m}:${s}`
            },
            onOkPop(value) {
                this.momentArrPop = value;
                if (this.momentArrPop != undefined && this.momentArrPop.length != 0) {
                    this.startTime = this.setTime(this.momentArrPop[0]);
                    this.endTime = this.setTime(this.momentArrPop[1]);
                }
                this.loadDeviceList();
            },
            onChangePop(dates) {
                this.momentArrPop = dates;
            },
            rangePickerValuePop() {
                return this.momentArrPop;
            }
        }
    }
</script>

<style scoped>
    /*组件样式*/
    /*文本框*/
    .ant-input {
        width: 200px;
        margin: 0 8px 8px 0;
    }

    .clickRowStyl {
        background-color: #C1E0FD;
    }

    .content {
        width: 100%;
        height: 100%;
    }

    .header-setting {
        width: 100%;
        height: 120px;
        background: #fff;
    }

    .header-setting .breadcrumb {
        margin-left: 41px;
        padding-top: 15px;
    }

    /* 表单 */
    .box-form {
        padding-left: 40px;
        padding-right: 40px;
        min-height: 705px;
        background: #fff;
        margin-top: 8px;
    }

    .box-form .box-tool {
        padding-top: 11px;
        margin: 8px 0;
        width: 100%;
        /* flex */
        display: flex;
        align-items: center;
        justify-content: space-between;
    }


    .box-condition-item {
        display: flex;
        align-items: center;
        min-width: 1500px;
        margin-top: 10px;
        margin-bottom: 10px;
        padding: 5px 0;
    }

    .button_online {
        margin-left: 62px;
        display: flex;
    }

    .button_online button {
        margin-right: 10px;
    }

    .box-tool button {
        margin-right: 10px;
    }

    /*-----------------设备日志/设备心跳--------------*/
    .box-form-others {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.6);
    }

    .box-form-others .form {
        width: 970.5px;
        height: 500px;
        padding-bottom: 20px;
        background: #fff;
        border-radius: 10px;
        /*max-height: ;*/

        position: fixed;
        left: 50%;
        top: 15%;
        transform: translate(-50%, 0);
        /* flex */
        display: flex;
        align-items: flex-start;
        flex-direction: column;
    }

    .box .box-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 5px 5px 20px 5px;
    }

    .button_time button {
        margin-left: 10px;
    }


</style>
